package com.atguigu.tingshu.user.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.PrivateKey;
import java.security.interfaces.RSAPrivateKey;

/**
 * 在项目启动的时候加载密钥文件中的私钥到容器
 *
 * @author Taeyang
 * @date 2025/4/25
 */
@Configuration
public class PrivateKeyConfig {

    /**
     * 加载私钥
     *
     * @return 私钥
     */
    @Bean
    public RSAPrivateKey rsaPrivateKeyInit() {
        // 加载jks文件
        ClassPathResource classPathResource = new ClassPathResource("tingshu.jks");
        // 获取文件中的秘钥
        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(classPathResource, "tingshu".toCharArray());
        // 获取中间的钥匙
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("tingshu", "tingshu".toCharArray());
        // 获取私钥
        return (RSAPrivateKey)keyPair.getPrivate();
    }
}
